<script lang="ts" setup>
import type { SystemMenuApi } from '#/api';

import { computed, nextTick, ref } from 'vue';

import { useVbenDrawer } from '@vben/common-ui';

import { Spin } from 'ant-design-vue';

import { useVbenForm } from '#/adapter/form';
import { createMenu, getMenuById, updateMenu } from '#/api/system';
import { $t } from '#/locales';

import { useFormSchema } from '../data';

const emits = defineEmits(['success']);

const formData = ref<SystemMenuApi.Menu>();
const loading = ref(false);

const [Form, formApi] = useVbenForm({
  schema: useFormSchema(),
  showDefaultActions: false,
  commonConfig: {
    colon: true,
    formItemClass: 'col-span-1', // 默认单列
  },
  wrapperClass: 'grid grid-cols-1 md:grid-cols-2 gap-x-4 gap-y-2', // 响应式2列布局
});

const id = ref();
const [Drawer, drawerApi] = useVbenDrawer({
  async onConfirm() {
    const { valid } = await formApi.validate();
    if (!valid) return;
    const values = await formApi.getValues();

    drawerApi.lock();

    await (
      id.value
        ? updateMenu({ ...values, id: id.value } as SystemMenuApi.Menu)
        : createMenu(values)
    )
      .then(() => {
        emits('success');
        drawerApi.close();
      })
      .catch(() => {
        drawerApi.unlock();
      });
  },

  async onOpenChange(isOpen) {
    if (isOpen) {
      const data = drawerApi.getData<SystemMenuApi.Menu>();
      formApi.resetForm();

      if (data?.id) {
        id.value = data.id;
        await loadMenuData(data.id);
      } else {
        id.value = undefined;
      }

      // Wait for Vue to flush DOM updates (form fields mounted)
      await nextTick();
      if (data) {
        formApi.setValues(data);
      }
    }
  },
});

async function loadMenuData(menuId: number | string) {
  try {
    loading.value = true;
    formData.value = await getMenuById(Number(menuId));
  } finally {
    loading.value = false;
  }
}

const getDrawerTitle = computed(() => {
  return formData.value?.id
    ? $t('common.edit', [$t('system.menu.name')])
    : $t('common.create', [$t('system.menu.name')]);
});
</script>

<template>
  <Drawer :title="getDrawerTitle" class="w-full max-w-[700px]">
    <Spin :spinning="loading">
      <Form class="px-6 py-4" />
    </Spin>
  </Drawer>
</template>

<style scoped>
/* 确保跨列元素在小屏幕上正常显示 */
@media (max-width: 768px) {
  :deep(.col-span-2) {
    grid-column: span 1;
  }
}

:deep(.ant-form-item) {
  margin-bottom: 16px;
}

/* 优化表单标签显示 */
:deep(.ant-form-item-label) {
  text-align: left;
}

/* 确保表单在小屏幕上也能正常显示 */
</style>
